<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="index !== '' ? addFn() : xiu()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click.prevent="del(index)">删除</button>
            <button @click.prevent="bianji(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "",
      age: "",
      sex: "",
      index: 0,
      list: [
        {
          name: "小红",
          age: 18,
          sex: "男",
        },
        {
          name: "小绿",
          age: 20,
          sex: "女",
        },
        {
          name: "小黑",
          age: 23,
          sex: "男",
        },
        {
          name: "小黄",
          age: 26,
          sex: "男",
        },
      ],
    };
  },
  methods: {
    addFn() {
      //判断是否有内容
      if (this.name.trim().length === 0 || this.age <= 0) {
        return alert("输入正确信息");
      }
      //push()添加  给list的数组添加数据
      this.list.push({
        name: this.name,
        age: this.age,
        sex: this.sex,
      });
      this.name = "";
      this.age = "";
      this.sex = "";
    },
    del(index) {
      this.list.splice(index, 1);
    },
    bianji(index) {
      this.name = this.list[index].name;
      this.age = this.list[index].age;
      this.sex = this.list[index].sex;
      this.index = index;
    },
    xiu() {
      this.$set(this.list, this.index, {
        name: this.name,
        name: this.age,
        name: this.sex,
      });
    },
  },
};
</script>